<template>
  <nav class="navbar">
    <!-- 背景装饰 -->
    <div class="navbar-bg"></div>

    <div class="navbar-container">
      <!-- Logo区域 -->
      <div class="navbar-brand">
        <div class="logo" @click="$router.push('/dashboard')">
          <span class="logo-icon">🎯</span>
          <span class="logo-text">Trainer</span>
        </div>
      </div>

      <!-- 导航菜单 -->
      <div class="navbar-menu">
        <router-link
          v-for="item in filteredMenuItems"
          :key="item.path"
          :to="item.path"
          class="nav-item"
          :class="{ active: $route.path === item.path }"
        >
          <span class="nav-icon">{{ item.icon }}</span>
          <span class="nav-text">{{ item.text }}</span>
        </router-link>
      </div>

      <!-- 用户区域 -->
      <div class="navbar-user">
        <!-- 已登录状态：显示用户信息 -->
        <div v-if="isLoggedIn" class="user-info" @click="toggleUserMenu">
          <div class="user-avatar">
            <img 
              v-if="isValidAvatar(user && user.avatar)" 
              :src="userAvatarUrl" 
              :alt="user.username || user.name || '用户'"
              class="avatar-img"
            />
            <span v-else class="avatar-icon">👤</span>
          </div>
          <div class="user-details">
            <span class="user-name">{{
              user.username || user.name || "用户"
            }}</span>
            <span class="user-status">在线</span>
          </div>
          <div class="dropdown-arrow" :class="{ rotated: showUserMenu }">
            <span>▼</span>
          </div>
        </div>

        <!-- 用户下拉菜单 -->
        <div class="user-dropdown" v-show="showUserMenu && isLoggedIn">
          <div class="dropdown-item" @click="handleProfile">
            <span class="dropdown-icon">👤</span>
            <span>个人中心</span>
          </div>
          <div class="dropdown-item" @click="handleAchievements">
            <span class="dropdown-icon">🏆</span>
            <span>成就勋章</span>
          </div>
          <div class="dropdown-item" @click="handleSettings">
            <span class="dropdown-icon">⚙️</span>
            <span>设置</span>
          </div>
          <div class="dropdown-divider"></div>
          <div class="dropdown-item logout" @click="handleLogout">
            <span class="dropdown-icon">🚪</span>
            <span>退出登录</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 登录注册弹框 -->
    <AuthModal
      :visible.sync="authModalVisible"
      :default-mode="authModalMode"
      @login-success="handleLoginSuccess"
      @close="handleAuthModalClose"
    />
  </nav>
</template>

<script>
import AuthModal from "./AuthModal.vue";
import { getAvatarUrl, isValidAvatar } from "@/utils/avatar.js";

export default {
  name: "AppNavbar",
  components: {
    AuthModal,
  },
  data() {
    return {
      showUserMenu: false,
      authModalVisible: false,
      authModalMode: "login",
      menuItems: [
        { path: "/dashboard", text: "首页", icon: "🏠" },
        { path: "/learn", text: "学习", icon: "📚" },
        { path: "/report", text: "数据报告", icon: "📈" },
        { path: "/knowledge-base", text: "知识库", icon: "📖" },
        { path: "/community", text: "社区", icon: "👥" },
      ],
    };
  },
  computed: {
    user() {
      return this.$store.state.user || {};
    },
    userAvatarUrl() {
      return getAvatarUrl(this.user && this.user.avatar);
    },
    isLoggedIn() {
      return (
        !!this.$store.state.user &&
        (!!this.$store.state.user.username || !!this.$store.state.user.name)
      );
    },
    // 根据登录状态过滤菜单项
    filteredMenuItems() {
      if (this.isLoggedIn) {
        // 登录后显示所有菜单
        return this.menuItems;
      } else {
        // 未登录时只显示首页和社区
        return this.menuItems.filter(item => 
          item.path === '/dashboard' || item.path === '/community'
        );
      }
    },
  },
  methods: {
    isValidAvatar,
    toggleUserMenu() {
      this.showUserMenu = !this.showUserMenu;
    },
    showAuthModal(mode) {
      this.authModalMode = mode;
      this.authModalVisible = true;
    },
    handleProfile() {
      this.showUserMenu = false;
      this.$router.push("/profile");
    },
    handleAchievements() {
      this.showUserMenu = false;
      this.$router.push("/achievements");
    },
    handleSettings() {
      this.showUserMenu = false;
      this.$router.push("/settings");
    },
    handleLogout() {
      this.showUserMenu = false;
      // 处理退出登录（清理JWT、本地缓存并回到首页）
      this.$store.dispatch("logout");
      this.$message.success('已退出登录');
      this.$router.push("/dashboard");
    },
    handleLoginSuccess(user) {
      // 登录成功后的处理
      this.$store.commit("setUser", user);
      this.$message.success("登录成功！");
      
      // 检查是否有重定向路径
      const redirectPath = this.$route.query.redirect;
      if (redirectPath) {
        // 清除查询参数并重定向到原页面
        this.$router.replace(redirectPath);
      }
    },
    handleAuthModalClose() {
      this.authModalVisible = false;
    },
  },
  mounted() {
    // 点击外部关闭用户菜单
    document.addEventListener("click", (e) => {
      if (!this.$el.contains(e.target)) {
        this.showUserMenu = false;
      }
    });
    
    // 监听token过期事件
    window.addEventListener('token-expired', () => {
      this.$store.dispatch('logout');
      this.$message.warning('登录已过期，请重新登录');
      this.showAuthModal('login');
    });
  },
  beforeDestroy() {
    // 移除事件监听器
    window.removeEventListener('token-expired', () => {});
  },
};
</script>

<style scoped>
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.navbar-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    135deg,
    rgba(245, 247, 250, 0.8) 0%,
    rgba(195, 207, 226, 0.8) 100%
  );
  pointer-events: none;
}

.navbar-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* Logo样式 */
.navbar-brand {
  flex-shrink: 0;
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 700;
  font-size: 1.5rem;
  text-decoration: none;
  transition: all 0.3s ease;
  cursor: pointer;
}



.logo-icon {
  font-size: 1.8rem;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.logo-text {
  background: #1e3a8a;
  background-clip: text;
}

/* 导航菜单 */
.navbar-menu {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  justify-content: center;
}

.nav-item {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 18px;
  color: #7f8c8d;
  text-decoration: none;
  border-radius: 25px;
  transition: all 0.3s ease;
  font-weight: 500;
  min-width: 90px;
  justify-content: center;
  white-space: nowrap;
}

.nav-item:hover {
  color: #3b82f6;
  background: rgba(59, 130, 246, 0.1);
  transform: translateY(-2px);
}

.nav-item.active {
  color: #3b82f6;
  background: linear-gradient(
    135deg,
    rgba(30, 58, 138, 0.15) 0%,
    rgba(59, 130, 246, 0.15) 100%
  );
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.2);
}

.nav-icon {
  font-size: 1.2rem;
  transition: transform 0.3s ease;
}

.nav-item:hover .nav-icon {
  transform: scale(1.1);
}

.nav-text {
  font-size: 0.9rem;
}



/* 用户区域 */
.navbar-user {
  position: relative;
  flex-shrink: 0;
}


.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  border-radius: 25px;
  background: rgba(59, 130, 246, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.user-info:hover {
  background: rgba(59, 130, 246, 0.15);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.2);
}

.user-info:active {
  transform: translateY(0px);
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(30, 58, 138, 0.3);
  overflow: hidden;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-icon {
  font-size: 1.2rem;
  color: white;
}

.user-details {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.user-name {
  font-weight: 600;
  color: #2c3e50;
  font-size: 0.9rem;
  line-height: 1.2;
}

.user-status {
  font-size: 0.75rem;
  color: #27ae60;
  font-weight: 500;
}

.dropdown-arrow {
  font-size: 0.7rem;
  color: #7f8c8d;
  transition: transform 0.3s ease;
}

.dropdown-arrow.rotated {
  transform: rotate(180deg);
}

/* 用户下拉菜单 */
.user-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 10px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
  min-width: 180px;
  overflow: hidden;
  animation: dropdownSlide 0.3s ease;
}

@keyframes dropdownSlide {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}



.dropdown-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  color: #2c3e50;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.9rem;
}

.dropdown-item:hover {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  transform: translateX(5px);
}

.dropdown-item.logout:hover {
  background: rgba(231, 76, 60, 0.1);
  color: #e74c3c;
  transform: translateX(5px);
}

.dropdown-icon {
  font-size: 1rem;
  width: 20px;
  text-align: center;
}

.dropdown-divider {
  height: 1px;
  background: rgba(0, 0, 0, 0.1);
  margin: 5px 0;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .navbar-container {
    max-width: 100%;
    padding: 0 15px;
  }

  .nav-item {
    min-width: 80px;
    padding: 10px 15px;
  }

  .nav-text {
    font-size: 0.85rem;
  }
}

@media (max-width: 768px) {
  .navbar-container {
    padding: 0 15px;
    height: 60px;
  }

  .logo-text {
    display: none;
  }

  .nav-text {
    display: none;
  }

  .nav-item {
    min-width: 60px;
    padding: 10px 15px;
  }

  .user-details {
    display: none;
  }

  .dropdown-arrow {
    display: none;
  }

  .user-info {
    padding: 6px 12px;
  }

}

@media (max-width: 480px) {
  .navbar-menu {
    gap: 2px;
  }

  .nav-item {
    min-width: 50px;
    padding: 8px 12px;
  }

  .nav-icon {
    font-size: 1rem;
  }

}
</style>